/* ========================================================================= */
/* ------------------------------------------------------------------------- */
/*!
  \file			mw.cc
  \date			Dec 2012
  \author		TNick

  \brief		Contains the implementation for MW class


*//*


 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 Please read COPYING and README files in root folder
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
/* ------------------------------------------------------------------------- */
/* ========================================================================= */
//
//
//
//
/*  INCLUDES    ------------------------------------------------------------ */

#include	<cpg/cpg.h>

#include	<cpg/editor-app/edstgs.h>
#include	<QCloseEvent>
#include	<QSettings>
#include	<QDesktopServices>
#include	<QPlainTextEdit>
#include	<QDialogButtonBox>

#include	"mw.h"

using namespace Gui;

/*  INCLUDES    ============================================================ */
//
//
//
//
/*  CLASS    --------------------------------------------------------------- */

/* ------------------------------------------------------------------------- */
MW::MW	( QWidget *parent ) :
	QMainWindow( parent ), ActionsHost()
{
	PGDBG2( PGDBG_CTORDTOR, "Creating main window", this );

	ui.setupUi( this );

	/* initialise the components */
	fileimpl_.init( this );
	editimpl_.init( this );
	helpimpl_.init( this );
	insertimpl_.init( this );
	mdiimpl_.init( this, ui.mdiArea );
	viewimpl_.init( this );

	/* file */
	fileimpl_.initMenu( ui.menu_File );
	fileimpl_.initToolbar( ui.tb_standard );
	connect( &mdiimpl_, SIGNAL(activeEditorChanged(EditorBase*)),
			 &fileimpl_, SLOT(activeEditorChanged(EditorBase*)) );
	connect( &fileimpl_, SIGNAL(editorCreated(EditorBase*)),
			 &fileimpl_, SLOT(addRecentFile(EditorBase*)) );
	connect( &mdiimpl_, SIGNAL(editorSaved(EditorBase*)),
			 &fileimpl_, SLOT(addRecentFile(EditorBase*)) );
	connect( &mdiimpl_, SIGNAL(openFileUReq(const QString &, const QString &)),
			 &fileimpl_, SLOT(slot_Open(const QString &, const QString &)) );
	connect( ui.mdiArea, SIGNAL(openFileReq(const QString &)),
			 &fileimpl_, SLOT(slot_Open(const QString &)) );


	/* edit */
	editimpl_.initMenu( ui.menu_Edit );
	editimpl_.initToolbar( ui.tb_standard );
	connect( &mdiimpl_, SIGNAL(activeEditorChanged(EditorBase*)),
			 &editimpl_, SLOT(activeEditorChanged(EditorBase*)) );
	connect( &fileimpl_, SIGNAL(editorCreated(EditorBase*)),
			 &editimpl_, SLOT(editorCreated(EditorBase*)) );
	connect( &mdiimpl_, SIGNAL(editorClosing(EditorBase*)),
			 &editimpl_, SLOT(editorClosing(EditorBase*)) );
	connect( this, SIGNAL(editorCursorMoved(EditorBase*,bool)),
			 &editimpl_, SLOT(editorCursorMoved(EditorBase*,bool)) );


	/* help */
	helpimpl_.initMenu( ui.menu_Help );


	/* insert */
	insertimpl_.initMenu( ui.menuInsert );
	insertimpl_.initToolbar( ui.tb_insert );
	connect( &mdiimpl_, SIGNAL(activeEditorChanged(EditorBase*)),
			 &insertimpl_, SLOT(activeEditorChanged(EditorBase*)) );


	/* mdi */
	mdiimpl_.initMenu( ui.menuWindow );
	connect( &fileimpl_, SIGNAL(editorCreated(EditorBase*)),
			 &mdiimpl_, SLOT(editorCreated(EditorBase*)) );
	connect( &fileimpl_, SIGNAL(editorCloseReq(EditorBase*)),
			 &mdiimpl_, SLOT(editorCloseReq(EditorBase*)) );
	connect( &fileimpl_, SIGNAL(editorSaveReq(EditorBase*)),
			 &mdiimpl_, SLOT(editorSaveReq(EditorBase*)) );
	connect( &fileimpl_, SIGNAL(editorSaveAsReq(EditorBase*)),
			 &mdiimpl_, SLOT(editorSaveAsReq(EditorBase*)) );


	/* view */
	viewimpl_.initMenu( ui.menu_View );
	connect( &mdiimpl_, SIGNAL(activeEditorChanged(EditorBase*)),
			 &viewimpl_, SLOT(activeEditorChanged(EditorBase*)) );


	/* this */
	connect( &mdiimpl_, SIGNAL(activeEditorChanged(EditorBase*)),
			 this, SLOT(activeEditorChanged(EditorBase*)) );
	connect( &fileimpl_, SIGNAL(editorCreated(EditorBase*)),
			 this, SLOT(editorCreated(EditorBase*)) );
	connect( &fileimpl_, SIGNAL(appEndReq()),
			 this, SLOT(close()) );
	connect( &editimpl_, SIGNAL(showPrefs()),
			 this, SLOT(showPrefs()) );
	connect( &mdiimpl_, SIGNAL(editorSaved(EditorBase*)),
			 this, SLOT(editorSaved(EditorBase*)) );
	connect( &mdiimpl_, SIGNAL(openLinkUReq(const QUrl &)),
			 this, SLOT(openLinkUReq(const QUrl &)) );
	connect( ui.statusbar, SIGNAL(customContextMenuRequested(QPoint)),
			 this, SLOT(statusMenuReq(const QPoint &)) );
	ui.statusbar->setContextMenuPolicy( Qt::CustomContextMenu );

	/* add toolbars to the menu */
	ui.menuToolbars->addAction(
				ui.tb_standard->toggleViewAction() );
	ui.menuToolbars->addAction(
				ui.tb_insert->toggleViewAction() );


	/* default position and size */
	QPoint pos( 0, 0 );
	QSize size( 800, 600 );

	move( pos );
	resize( size );
	show();

	/* main panel position and size */
	QSettings settings;
	settings.beginGroup("MW");

	restoreGeometry( settings.value( "geom" ).toByteArray() );
	restoreState( settings.value( "state" ).toByteArray() );

	settings.endGroup();

	logMessage(tr("Application ready"));

}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
MW::~MW	( void )
{
	PGDBG2( PGDBG_CTORDTOR, "Destroyng main window", this );
	/* stub */
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void					MW::changeEvent			( QEvent * e )
{
	QMainWindow::changeEvent( e );
	switch ( e->type() ) {
	case QEvent::LanguageChange:	{
		ui.retranslateUi( this );
		break;}
	default:						{
		break;}
	}
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void					MW::closeEvent					( QCloseEvent *e )
{
	PGDBG2( PGDBG_MW, "FileImpl: close event", this );
	PGDBG( PGDBG_MW, "  - attempt to close documents" );

	if ( mdiimpl_.closeAll() == false )
	{
		e->ignore();
		return;
	}

	fileimpl_.end();
	editimpl_.end();
	helpimpl_.end();
	insertimpl_.end();
	mdiimpl_.end();
	viewimpl_.end();

	QSettings settings;
	settings.beginGroup("MW");

//	settings.setValue( "pos", pos() );
//	settings.setValue( "size", size() );

	settings.setValue( "geom", saveGeometry() );
	settings.setValue( "state", saveState() );

	e->accept();
	settings.endGroup();
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void					MW::editorCreated				( EditorBase * ed )
{
	connect( ed->asWidget(), SIGNAL( selectionChanged() ),
			 this, SLOT(editorSelChanged())
			 );
	connect( ed->asWidget(), SIGNAL( contextMenu(QPoint) ),
			 this, SLOT(contextMenu(QPoint))
			 );

	connect( ed->asWidget(), SIGNAL( exportStarted() ),
			 this, SLOT( exportStarted() )
			 );
	connect( ed->asWidget(), SIGNAL( outputFileOpened(const QString &) ),
			 this, SLOT( outputFileOpened(const QString &) )
			 );
	connect( ed->asWidget(), SIGNAL( exportEnded(bool) ),
			 this, SLOT( exportEnded(bool) )
			 );

	logMessage( tr( "New document opened: %1" ).arg( ed->documentName() ) );
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void					MW::contextMenu					( const QPoint & pt )
{
	PGDBG2( PGDBG_MW, "EdWebKit: contextual menu", sender() );
	PGDBG2( PGDBG_MW, "  - point:", pt );

	QWidget * w = static_cast<QWidget*>( sender() );
	QMenu	m;

	editimpl_.initCtxMenu( &m );

	m.exec( w->mapToGlobal( pt ) );
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void					MW::showPrefs					( void )
{
	EdStgs eds( this );

//	StgsLib sl;
//	StgsOut so;

//	eds.addPage( &sl );
//	eds.addPage( &so );

	if ( eds.start() == QDialog::Accepted )
	{
		/* do sth, be happy ... */
	}
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
bool					MW::openFile					( const QString & s_file )
{
	return fileimpl_.slot_Open( s_file );
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void					MW::logMessage					(const QString & s )
{
	ui.statusbar->showMessage( s );
	QString s_log = ui.statusbar->toolTip();
	if ( s_log.isEmpty() == false )
	{
		s_log.append( "\n" );
	}
	s_log.append( s );
	ui.statusbar->setToolTip( s_log );
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void					MW::activeEditorChanged			( EditorBase * ed )
{
	if ( ed != NULL )
	{
		emit editorCursorMoved( ed, ed->hasSelection() );
		setWindowTitle( tr("GitPlayG - %1[*]").arg( ed->documentName() ) );
		setWindowModified( ed->isModified() );
	}
	else
	{
		setWindowTitle( tr("GitPlayG") );
	}
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void					MW::editorSelChanged			( void )
{
	EditorBase * ed = mdiimpl_.editorForObject( sender() );
	if ( ed == NULL )
		return;
	if ( ed == crtEditor() )
	{
		emit editorCursorMoved(
					ed,
					ed->hasSelection() );
		setWindowModified( ed->isModified() );
	}
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void					MW::editorSaved					( EditorBase * ed )
{
	if ( ed == NULL )
		return;
	if ( ed == crtEditor() )
	{
		setWindowTitle( tr("GitPlayG - %1[*]").arg( ed->documentName() ) );
		setWindowModified( ed->isModified() );
	}
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void					MW::openLinkUReq				( const QUrl & url )
{
	/** @todo V2.0 implement opening as read only web pages */
	QDesktopServices::openUrl( url );
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void					MW::outputFileOpened			( const QString & s )
{
	logMessage( tr("\tCreated file %1").arg( s ) );
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void					MW::exportStarted				( void )
{
	logMessage( tr("Exporting content from %1").arg(
					crtEditor()->documentName() ) );
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void					MW::exportEnded					( bool b_res )
{
	if ( b_res )
	{
		logMessage( tr("Exporting was successful.") );
	}
	else
	{
		logMessage( tr("Exporting failed.") );
	}
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void					MW::statusMenuReq				( const QPoint & pt )
{
	QMenu		m;
	QAction		ac_edit_log( tr( "Edit log..." ), NULL );
	QAction *	result;

	m.addAction( &ac_edit_log );

	result = m.exec( ui.statusbar->mapToGlobal( pt ) );
	if ( result == NULL )
	{
		return;
	}
	else if ( result == &ac_edit_log )
	{
		QDialog d;
		QVBoxLayout vl;
		QDialogButtonBox dbox;
		QPlainTextEdit txed;
		d.setLayout( &vl );
		vl.addWidget( &txed );
		vl.addWidget( &dbox );
		dbox.setStandardButtons(
					QDialogButtonBox::Ok |
					QDialogButtonBox::Cancel );
		connect( &dbox, SIGNAL( accepted() ), &d, SLOT( accept()) );
		connect( &dbox, SIGNAL( rejected() ), &d, SLOT( reject() ) );
		txed.setPlainText( ui.statusbar->toolTip() );
		d.setWindowTitle( tr("Log messages") );

		if ( d.exec() == QDialog::Accepted )
		{
			ui.statusbar->setToolTip( txed.toPlainText() );
		}
	}
	else
	{
		Q_ASSERT( false );
	}
}
/* ========================================================================= */



/*  CLASS    =============================================================== */
//
//
//
//
/* ------------------------------------------------------------------------- */
/* ========================================================================= */
